package com.heima.behavior.service.imp;

import com.alibaba.fastjson.JSON;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApReadBehaviorService;
import com.heima.common.constants.article.HotArticleConstants;
import com.heima.model.behavior.dtos.ReadBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApReadBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.mess.app.UpdateArticleMess;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import com.mongodb.client.result.UpdateResult;
import io.swagger.annotations.Authorization;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ThreadUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import javax.websocket.server.ServerEndpoint;
import java.util.Date;

/**
 * @作者 Azer
 * @创建日期 2021/11/27 17:11
 **/
@Service
@Slf4j
public class ApReadBehaviorServiceImpl implements ApReadBehaviorService {
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Autowired
    MongoTemplate mongoTemplate;

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Override
    public ResponseResult readBehavior(ReadBehaviorDTO dto) {
//        ApReadBehavior apReadBehavior=new ApReadBehavior();



//        1. 校验参数 文章id必须传
//        2. 根据登录用户id 或 设备id查询行为实体数据(阅读操作可不登录)
        ApUser apUser = AppThreadLocalUtils.getUser();
        Integer apUserId = apUser.getId();

        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUserId, dto.getEquipmentId());

//        3. 判断阅读行为是否存在

        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));

        ApReadBehavior apReadBehaviorOne = mongoTemplate.findOne(query, ApReadBehavior.class);
        if(apReadBehaviorOne!=null){
//            4. 存在  将阅读行为的count字段加1 并修改
            Update update=new Update();
            update.set("count",apReadBehaviorOne.getCount()+1).set("updatedTime",new Date());

            mongoTemplate.updateMulti(query, update, ApReadBehavior.class);
            log.info("阅读行为成功");
//            return ResponseResult.okResult();
        }
//        5. 不存在  创建阅读行为 并初始化count字段值为 1
        if(apReadBehaviorOne==null){
            apReadBehaviorOne=new ApReadBehavior();
            BeanUtils.copyProperties(dto,apReadBehaviorOne);
            apReadBehaviorOne.setEntryId(apBehaviorEntry.getId());
            apReadBehaviorOne.setCount((short)1);
            apReadBehaviorOne.setUpdatedTime(new Date());
            mongoTemplate.save(apReadBehaviorOne);
            log.info("阅读行为初始化成功");

//            return ResponseResult.okResult();
        }
        // =======================新加代码==========================
        UpdateArticleMess mess = new UpdateArticleMess();
        mess.setType(UpdateArticleMess.UpdateArticleType.VIEWS);
        mess.setArticleId(dto.getArticleId());
        mess.setAdd(1);
        rabbitTemplate.convertAndSend(HotArticleConstants.HOT_ARTICLE_SCORE_BEHAVIOR_QUEUE, JSON.toJSONString(mess));
        log.info("阅读行为 发送消息 ==>{}",mess);
        // =======================新加代码==========================

        return ResponseResult.okResult();
    }
}
